package cn.bistu.cs.music;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class PlayerActivity extends AppCompatActivity {
    private TextView title;
    private TextView name;
    private MediaPlayer mediaPlayer;
    private SeekBar seekBar;
    private TextView current_time;
    private TextView total_time;
    private Handler handler;
    private Cursor cursor;
    private ImageView btn_previous;
    private ImageView btn_play_or_pause;
    private ImageView btn_next;
    private Timer timer;
    private int tag=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acticity_player);
        initView();
        initData();
        initPlay();
        initSeek();
        moveSeek();//拖动进度
        initUpdate();//及时更新进度
        setListioner();//监听器
    }

    /**
     * 输入当前游标位置,启动mediaPlayer
     * @param cursor
     */
    @SuppressLint("Range")
    private void openMedia(Cursor cursor){
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
        mediaPlayer.reset();
        try {
            Log.e("mediaPlayer:",path);
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.start();
            String musicTitle = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String musicSinger = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            title.setText(musicTitle);
            name.setText(musicSinger);
            btn_play_or_pause.setImageDrawable(null);
            tag=0;
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    private final class CompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            if(!cursor.isLast()){
                cursor.moveToNext();
            }else {
                cursor.moveToFirst();
            }
            openMedia(cursor);
        }

    }
    private void setListioner() {
        mediaPlayer.setOnCompletionListener(new CompletionListener());
        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!cursor.isLast()){
                    cursor.moveToNext();
                }else {
                    cursor.moveToFirst();
                }
                openMedia(cursor);
            }
        });
        btn_previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Log.e("cursor位置",""+cursor.getPosition());
                if (!cursor.isFirst()){
                    cursor.move(-1);
                }else
                    cursor.moveToLast();
                openMedia(cursor);
            }
        });
        btn_play_or_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(tag==0){
                    mediaPlayer.pause();
                    tag=1;
                    btn_play_or_pause.setImageDrawable(getResources().getDrawable(R.drawable.paly));
//                    btn_play_or_pause.setPressed(true);
                }else{
                    mediaPlayer.start();
                    tag=0;
                    btn_play_or_pause.setImageDrawable(null);
//                    btn_play_or_pause.setPressed(false);
                }
            }
        });
    }

    private void initView() {
        title = findViewById(R.id.player_title);
        name = findViewById(R.id.player_name);
        current_time = findViewById(R.id.current_time);
        total_time = findViewById(R.id.total_time);
        seekBar =  findViewById(R.id.seek_bar);
        btn_previous = findViewById(R.id.btn_previous);
        btn_play_or_pause = findViewById(R.id.btn_play_or_pause);
        btn_next = findViewById(R.id.btn_next);
    }
    @SuppressLint("Range")
    private void initData() {
        int position = getIntent().getIntExtra("myPosition",0);
        Log.e("PlayerActivity定位",position+"");
        cursor = getApplicationContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        while(cursor.moveToNext()){
            System.out.println(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
        }
        cursor.moveToFirst();
        cursor.moveToPosition(position);
        Log.e("cursor的位置2",cursor.getPosition()+"");
        String musicTitle = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
        String musicSinger = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
        title.setText(musicTitle);
        name.setText(musicSinger);
        Log.e("点击的音乐是：",musicTitle);
    }
    @SuppressLint("Range")
    private void initPlay(){
        mediaPlayer = new MediaPlayer();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
        mediaPlayer.reset();
        try {
            Log.e("mediaPlayer:",path);
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.start();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    private void initSeek(){
        seekBar.setMax(mediaPlayer.getDuration());
        seekBar.setProgress(mediaPlayer.getCurrentPosition());
        current_time.setText(toTime(mediaPlayer.getCurrentPosition()));
        total_time.setText(toTime(mediaPlayer.getDuration()));
    }
    private void initUpdate(){
        timer = new Timer();
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 11:
                        initSeek();
                        break;
                    default:
                        break;
                }
            }
        };
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 11;
                handler.sendMessage(msg);
            }
        };
        timer.schedule(timerTask,0,100);
    }

    /**
     * 自定义时间格式
     * @param time
     * @return
     */
    public String toTime(int time) {
        String s = null;
        if (time / 1000 % 60 < 10) {
            s = time / 1000 / 60 + ":0" + time / 1000 % 60;
        } else {
            s = time / 1000 / 60 + ":" + time / 1000 % 60;
        }
        return s;
    }

    protected void moveSeek(){
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mediaPlayer.seekTo(progress);
                    initSeek();
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
        cursor.close();
        timer.cancel();
    }
}